package com.gouqi.tools.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.gouqi.gouqitoolscommon.model.entity.Tool;
import com.gouqi.gouqitoolscommon.model.entity.User;
import com.gouqi.tools.common.ErrorCode;
import com.gouqi.tools.constant.CommonConstant;
import com.gouqi.tools.exception.BusinessException;
import com.gouqi.tools.exception.ThrowUtils;
import com.gouqi.tools.mapper.ToolMapper;
import com.gouqi.tools.model.dto.tool.ToolQueryRequest;
import com.gouqi.tools.model.vo.ToolVO;
import com.gouqi.tools.model.vo.UserVO;
import com.gouqi.tools.service.ToolService;
import com.gouqi.tools.service.UserService;
import com.gouqi.tools.utils.SqlUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @description 针对表【tool(工具信息)】的数据库操作Service实现
 */
@Service
public class ToolServiceImpl extends ServiceImpl<ToolMapper, Tool>
        implements ToolService {

    private final static Gson GSON = new Gson();

    @Resource
    private UserService userService;

    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Override
    public void validTool(Tool tool, boolean add) {
        //如果工具信息为空，为空抛出异常
        if (tool == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String name = tool.getName();
        String description = tool.getDescription();

        // 创建时，参数不能为空
        if (add) {
            ThrowUtils.throwIf(StringUtils.isAnyBlank(name), ErrorCode.PARAMS_ERROR);
        }
        // 有参数则校验
        if (StringUtils.isNotBlank(name) && name.length() > 80) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "名称过长");
        }
        if (StringUtils.isNotBlank(description) && description.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "描述过长");
        }
    }

    /**
     * 获取查询包装类
     *
     * @param toolQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Tool> getQueryWrapper(ToolQueryRequest toolQueryRequest) {
        QueryWrapper<Tool> queryWrapper = new QueryWrapper<>();
        if (toolQueryRequest == null) {
            return queryWrapper;
        }
        String logo = toolQueryRequest.getLogo();
        String name = toolQueryRequest.getName();
        String description = toolQueryRequest.getDescription();
        String url = toolQueryRequest.getUrl();
        String requestHeader = toolQueryRequest.getRequestHeader();
        String responseHeader = toolQueryRequest.getResponseHeader();
        Integer status = toolQueryRequest.getStatus();
        String method = toolQueryRequest.getMethod();
        String userId = toolQueryRequest.getUserId();
        long current = toolQueryRequest.getCurrent();
        long pageSize = toolQueryRequest.getPageSize();
        String sortField = toolQueryRequest.getSortField();
        String sortOrder = toolQueryRequest.getSortOrder();
        // 拼接查询条件
        if (StringUtils.isNotBlank(description)) {
            queryWrapper.like("description", description).or().like("description", description);
        }
        queryWrapper.like(StringUtils.isNotBlank(name), "name", name);
        queryWrapper.like(StringUtils.isNotBlank(url), "url", url);
        queryWrapper.eq(status >= 0, "status", status);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    @Override
    public ToolVO getToolVO(Tool tool, HttpServletRequest request) {
        String userId = tool.getUserId();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(userId), "id", userId);
        User user = userService.list(queryWrapper).get(0);
        ToolVO toolVO = ToolVO.objToVo(tool);
        toolVO.setUser(userService.getUserVO(user));
        return toolVO;
    }

    @Override
    public Page<ToolVO> getToolVOPage(Page<Tool> toolPage, HttpServletRequest request) {
        List<Tool> toolList = toolPage.getRecords();
        Page<ToolVO> toolVOPage = new Page<>(toolPage.getCurrent(), toolPage.getSize(), toolPage.getTotal());
        if (CollectionUtils.isEmpty(toolList)) {
            return toolVOPage;
        }
        // 1. 关联查询用户信息
        Set<String> userIdSet = toolList.stream().map(Tool::getUserId).collect(Collectors.toSet());
        Map<String, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 填充信息
        List<ToolVO> toolVOList = toolList.stream().map(tool -> {
            ToolVO toolVO = ToolVO.objToVo(tool);
            String userId = tool.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            toolVO.setUser(userService.getUserVO(user));
            return toolVO;
        }).collect(Collectors.toList());
        toolVOPage.setRecords(toolVOList);
        return toolVOPage;
    }


}




